package saucaca.fragment;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.SongObject;
import saucaca.Util.AppController;
import saucaca.Util.CMD;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.lemon.kenhnhacvn.BaseActivity;
import com.lemon.kenhnhacvn.BaseEngine;
import com.lemon.kenhnhacvn.MainActivity;
import com.lemon.kenhnhacvn.R;
import com.lemon.kenhnhacvn.VideoPlayActivity;

public class VideoDetaisFragment extends Fragment {
	static String SETLIST = "setlist";
	TextView txtTitle, txtArtist, txtViewed, txtLike;
	ListView listView;
	CustomAdapterVideoListview adapter;
	ArrayList<SongObject> listsongs;
	Context context;
	SongObject songObject;
	private ProgressBar bar;

	public static VideoDetaisFragment newInstance(ArrayList<SongObject> listsongs, SongObject songObject) {
		VideoDetaisFragment f = new VideoDetaisFragment();
		Bundle args = new Bundle();
		args.putSerializable(MainActivity.INDEX, songObject);
		args.putSerializable(MainActivity.ID, listsongs);
		f.setArguments(args);
		return f;
	}

	public static VideoDetaisFragment newInstance(SongObject songObject) {
		VideoDetaisFragment f = new VideoDetaisFragment();
		Bundle args = new Bundle();
		args.putSerializable(MainActivity.INDEX, songObject);
		f.setArguments(args);
		return f;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.video_details_listsuggest, null);
		findviewById(view);
		context = getActivity();
		Bundle arguments = getArguments();
		if (arguments != null && arguments.containsKey(MainActivity.INDEX))
			songObject = (SongObject) arguments.getSerializable(MainActivity.INDEX);
		if (arguments != null && arguments.containsKey(MainActivity.ID))
			listsongs = (ArrayList<SongObject>) arguments.getSerializable(MainActivity.ID);

		txtTitle.setText(songObject.getTXNAME());
		txtArtist.setText(songObject.getNAME_SINGERS());
		if (songObject.getFormNet()) {
			txtViewed.setText(BaseEngine.convertStringLongtoInteger(songObject.getISVIEW()));
			txtLike.setText(BaseEngine.convertStringLongtoInteger(songObject.getISLIKE()));
			if (listsongs == null) {
				listsongs = new ArrayList<SongObject>();
			} else
				bar.setVisibility(View.GONE);
			adapter = new CustomAdapterVideoListview(context, listsongs);
			// new songDetailsServices().execute("");
		} else {
			this.listsongs = new ArrayList<SongObject>();
			for (int i = 0; i < LocalAllMusic.allVideoMap.size(); i++) {
				if (!((SongObject) LocalAllMusic.allVideoMap.get(i).get(LocalAllMusic.Key_Music)).getPATCH_FULL().equals(songObject.getPATCH_FULL()))
					listsongs.add((SongObject) LocalAllMusic.allVideoMap.get(i).get(LocalAllMusic.Key_Music));
			}
			txtViewed.setVisibility(View.GONE);
			txtLike.setVisibility(View.GONE);
			adapter = new CustomAdapterVideoListview(context, listsongs);
			bar.setVisibility(View.GONE);
		}
		listView.setAdapter(adapter);
		return view;
	}

	void findviewById(View view) {
		txtTitle = (TextView) view.findViewById(R.id.video_details_title);
		txtArtist = (TextView) view.findViewById(R.id.video_details_artist);
		txtViewed = (TextView) view.findViewById(R.id.video_details_textluotnghe);
		bar = (ProgressBar) view.findViewById(R.id.videoplayerPreloader);
		txtLike = (TextView) view.findViewById(R.id.video_details_textYeuthich);
		listView = (ListView) view.findViewById(R.id.video_details_listview);
	}

	class songDetailsServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.idDetais(CMD.CMD_SONG_DETAIL, songObject.getSONG_ID());
			// BaseEngine.showLogformLongString(str);
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					songObject = JsonReader.readSongdetail(result).get(0);
					txtTitle.setText(songObject.getTXNAME());
					txtArtist.setText(songObject.getNAME_SINGERS());
					if (songObject.getFormNet()) {
						txtViewed.setText(BaseEngine.convertStringLongtoInteger(songObject.getISVIEW()));
						txtLike.setText(BaseEngine.convertStringLongtoInteger(songObject.getISLIKE()));
					}
					listsongs = JsonReader.readListsong(result);
					listView.setAdapter(new CustomAdapterVideoListview(getActivity(), listsongs));
					bar.setVisibility(View.GONE);
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}

	public class CustomAdapterVideoListview extends ArrayAdapter<SongObject> {
		Context context;
		List<SongObject> data = new ArrayList<SongObject>();
		ImageLoader imageLoader;
		boolean isBXH = false;

		public CustomAdapterVideoListview(Context context, List<SongObject> data) {
			super(context, R.layout.item_bxh_listview, data);
			this.context = context;
			this.data = data;
			try {
				imageLoader = ((BaseActivity) getActivity()).imageLoader;
			} catch (Exception e) {
				imageLoader = AppController.getInstance().getImageLoader();
			}
		}

		public void setListVideo(List<SongObject> data) {
			this.data = data;
			for (int i = 0; i < data.size(); i++) {
				data.get(i).showSonginfo();
			}
			notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			RecordHolder holder = null;
			if (row == null) {
				LayoutInflater inflater = ((Activity) context).getLayoutInflater();
				row = inflater.inflate(R.layout.item_bxh_listview, parent, false);
				holder = new RecordHolder();
				holder.relati_Rank = (RelativeLayout) row.findViewById(R.id.item_bxh_relativeRank);
				holder.relati_Yeuthich = (RelativeLayout) row.findViewById(R.id.item_bxh_retaliYeuthich);
				holder.txtTitle = (TextView) row.findViewById(R.id.item_bxh_title);
				holder.txtArtist = (TextView) row.findViewById(R.id.item_bxh_artist);
				holder.imageItem = (ImageView) row.findViewById(R.id.item_bxh_imgAvatar);
				holder.txtLuotnghe = (TextView) row.findViewById(R.id.item_bxh_textluotnghe);
				holder.txtYeuthich = (TextView) row.findViewById(R.id.item_bxh_textYeuthich);
				holder.txtRank = (TextView) row.findViewById(R.id.item_bxh_textViewRank);
				holder.imgVideoicon = (ImageView) row.findViewById(R.id.item_bxh_Videoicon);
				holder.imgRank = (ImageView) row.findViewById(R.id.item_bxh_imgRankColor);
				row.setTag(holder);
			} else {
				holder = (RecordHolder) row.getTag();
			}
			final SongObject item = data.get(position);
			if (!item.getFormNet()) {
				long ids = Long.parseLong(item.getSONG_ID());
				ContentResolver crThumb = context.getContentResolver();
				BitmapFactory.Options options = new BitmapFactory.Options();
				options.inSampleSize = 1;
				Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND, options);
				holder.imageItem.setImageBitmap(curThumb);
			} else{
				
//				imageLoader.displayImage(item.getAVATAR(), holder.imageItem);
				imageLoader.get(item.getAVATAR(), ImageLoader.getImageListener(holder.imageItem,
				         R.drawable.ic_default, R.drawable.ic_default));
			}
			if (isBXH == false) {
				holder.relati_Rank.setVisibility(View.INVISIBLE);
				holder.relati_Yeuthich.setVisibility(View.INVISIBLE);
			}
			holder.txtTitle.setText(item.getTXNAME());
			holder.txtArtist.setText(item.getNAME_SINGERS());
			holder.txtRank.setText(Integer.toString((position + 1)));
			holder.txtLuotnghe.setText(BaseEngine.convertStringLongtoInteger(item.getISVIEW()));
			holder.txtYeuthich.setText("0");
			row.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					bar.setVisibility(View.VISIBLE);
					songObject = item;
					txtTitle.setText(item.getTXNAME());
					((VideoPlayActivity) context).songObject = item;
					((VideoPlayActivity) context).playVideo();
					listsongs.clear();
					if (!songObject.getFormNet()) {
						for (int i = 0; i < LocalAllMusic.allVideoMap.size(); i++) {
							if (!((SongObject) LocalAllMusic.allVideoMap.get(i).get(LocalAllMusic.Key_Music)).getPATCH_FULL().equals(songObject.getPATCH_FULL()))
								listsongs.add((SongObject) LocalAllMusic.allVideoMap.get(i).get(LocalAllMusic.Key_Music));
							setListVideo(listsongs);
						}
						bar.setVisibility(View.GONE);
					} else {
//						ArrayList<SongObject> listsong = new ArrayList<SongObject>();
//						for (int i = 0; i < listsongs.size(); i++) {
//							if (!listsongs.get(i).getPATCH_FULL().equals(songObject.getPATCH_FULL()))
//								listsong.add(listsongs.get(i));
//						}
//						setListVideo(listsong);
//						bar.setVisibility(View.GONE);
						adapter.notifyDataSetChanged();
						new songDetailsServices().execute("");
					}
				}
			});
			return row;
		}

		class RecordHolder {
			RelativeLayout relati_Rank;
			RelativeLayout relati_Yeuthich;
			ImageView imgRank;
			ImageView imgVideoicon;
			ImageView imageItem;
			TextView txtLuotnghe;
			TextView txtYeuthich;
			TextView txtRank;
			TextView txtTitle;
			TextView txtArtist;
		}
	}

}
